<template>
  <div class="app-container">
    <el-card class="content-edit" >
      <div slot="header">{{ pageType==='add'?'添加路线':'编辑路线' }}</div>
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="线路名称" maxlength="20">
          <el-input v-model="form['name']"/>
        </el-form-item>
        <el-form-item label="线路属性" maxlength="20">
          <el-radio-group v-model="form['hot']">
            <el-radio label="1">普通路线</el-radio>
            <el-radio label="2">热门路线</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出发地">
          <el-select v-model="form['provinceCodeFromIdx']" placeholder="请选择省份" filterable
                     @change="e=>provinceSelectChange(e, 'From')">
            <el-option v-for="(item,index) in provinceList" :key="item.code" :label="item.name" :value="index"/>
          </el-select>
          <el-select v-model="form['cityCodeFromIdx']" placeholder="请选择市" filterable
                     @change="e=>citySelectChange(e, 'From')">
            <el-option v-for="(item,index) in FromCityList" :key="item.code" :label="item.name" :value="index"/>
          </el-select>
          <el-select v-if="FromAreaList.length!=0" v-model="form['areaCodeFrom']" placeholder="请选择区" filterable>
            <el-option v-for="item in FromAreaList" :key="item.code" :label="item.name" :value="item.code"/>
          </el-select>
          <el-input v-model="form['addressFrom']" :rows="2" type="textarea" placeholder="详细地址"/>
        </el-form-item>
        <el-form-item label="目的地">
          <el-select v-model="form['provinceCodeToIdx']" placeholder="请选择省份" filterable
                     @change="e=>provinceSelectChange(e, 'To')">
            <el-option v-for="(item,index) in provinceList" :key="item.code" :label="item.name" :value="index"/>
          </el-select>
          <el-select v-model="form['cityCodeToIdx']" placeholder="请选择市" filterable
                     @change="e=>citySelectChange(e, 'To')">
            <el-option v-for="(item,index) in ToCityList" :key="item.code" :label="item.name" :value="index"/>
          </el-select>
          <el-select v-if="ToAreaList.length!=0" v-model="form['areaCodeTo']" placeholder="请选择区" filterable>
            <el-option v-for="item in ToAreaList" :key="item.code" :label="item.name" :value="item.code"/>
          </el-select>
          <el-input v-model="form['addressTo']" :rows="2" type="textarea" placeholder="详细地址"/>
        </el-form-item>
        <el-form-item label="车型选择">
          <el-select v-model="form['carType']" placeholder="车辆类型">
            <el-option v-for="item in carTypeList" :key="item.id" :value="item['id']" :label="item['name']"/>
          </el-select>
        </el-form-item>
        <el-form-item label="车票价格" class="ticket">
          <div class="item">
            <span @click.stop.prevent="radioClick('openDefault')">
              <el-radio v-model="form['openDefault']" :label="1">&nbsp;</el-radio>
            </span>
            <span>默认</span>
            <div>
              <el-input v-model="form['defaultAdultPrice']" type="number" class="ticket-input">
                <span slot="prepend">成人</span>
                <span slot="suffix" class="span">元</span>
              </el-input>
              <el-input v-model="form['defaultChildrenPrice']" type="number" class="ticket-input">
                <span slot="prepend">儿童</span>
                <span slot="suffix" class="span">元</span>
              </el-input>
              <el-input v-model="form['defaultCommission']" type="number" class="ticket-input">
                <span slot="prepend">佣金</span>
                <span slot="suffix" class="span">元</span>
              </el-input>
            </div>
          </div>
          <div class="item">
            <span @click.stop.prevent="radioClick('openWeekend')">
              <el-radio v-model="form['openWeekend']" :label="1">&nbsp;</el-radio>
            </span>
            <span>周末</span>
            <div>
              <el-input v-model="form['weekendAdultPrice']" type="number" class="ticket-input">
                <span slot="prepend">成人</span>
                <span slot="suffix" class="span">元</span>
              </el-input>
              <el-input v-model="form['weekendChildrenPrice']" type="number" class="ticket-input">
                <span slot="prepend">儿童</span>
                <span slot="suffix" class="span">元</span>
              </el-input>
              <el-input v-model="form['weekendCommission']" type="number" class="ticket-input">
                <span slot="prepend">佣金</span>
                <span slot="suffix" class="span">元</span>
              </el-input>
            </div>
          </div>
          <div class="item">
            <span @click.stop.prevent="radioClick('openDate')">
              <el-radio v-model="form['openDate']" :label="1">&nbsp;</el-radio>
            </span>
            <span>指定日期</span>
            <el-date-picker
              v-model="form['dateBetween']"
              class="margin-left-20"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"/>
            <div>
              <el-input v-model="form['dateAdultPrice']" type="number" class="ticket-input">
                <span slot="prepend">成人</span>
                <span slot="suffix" class="span">元</span>
              </el-input>
              <el-input v-model="form['dateChildrenPrice']" type="number" class="ticket-input">
                <span slot="prepend">儿童</span>
                <span slot="suffix" class="span">元</span>
              </el-input>
              <el-input v-model="form['dateCommission']" type="number" class="ticket-input">
                <span slot="prepend">佣金</span>
                <span slot="suffix" class="span">元</span>
              </el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="荷载人数">
          <el-input v-model="form['rideNumber']" type="number" style="width: 140px"/>
        </el-form-item>
        <el-form-item label="可售车票">
          <el-input v-model="form['ticketNumber']" type="number" style="width: 140px"/>
        </el-form-item>
        <el-form-item label="班次">
          <el-input v-model="form['shifts']" style="width: 210px">
            <span slot="suffix" style="margin-right: 10px;line-height: 40px;">分钟/班</span>
          </el-input>
        </el-form-item>
        <el-form-item label="司机选择">
          <el-select v-model="form['driver']" multiple filterable placeholder="请选择司机" style="width: 460px;">
            <el-option v-for="item in driverList" :key="item.id" :label="item['nickname']" :value="item.id">{{ item['nickname'] }}
              <span class="margin-right-20" style="float: right; color: #8492a6; font-size: 13px">{{ item['mobile'] }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运营时间">
          <el-time-picker
            v-model="form['operationTime']"
            is-range
            clearable
            range-separator="-"
            value-format="HH:mm:ss"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"/>
        </el-form-item>
        <el-form-item label="售票截止时间">
          发车前 <el-input v-model="form['ticketDeadline']" :min="0" type="number" style="width: 80px"/> 分钟停止售票
        </el-form-item>
        <el-form-item label="售票运营时间">
          <el-time-picker
            v-model="form['ticketingTime']"
            is-range
            clearable
            range-separator="-"
            value-format="HH:mm"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"/>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
  export default {
    name: 'RouteDailyModify',
    data() {
      return {
        pageType: 'add',
        loading: false,
        // 司机列表
        driverList: [],
        // 车辆类型列表
        carTypeList: [],
        // 省市区列表
        provinceList: [],
        // 出发地市列表
        FromCityList: [],
        // 出发地区列表
        FromAreaList: [],
        // 出发地市列表
        ToCityList: [],
        // 出发地区列表
        ToAreaList: [],

        form: {
          // 路线名称
          name: '',
          // 路线属性
          hot: '1',
          // 车辆类型
          carType: '',
          // 出发地
          // 省
          provinceCodeFromIdx: '',
          provinceCodeFrom: '',
          // 市
          cityCodeFromIdx: '',
          cityCodeFrom: '',
          // 区
          areaCodeFrom: '',
          // 详细地址
          addressFrom: '',
          // 目的地
          // 省
          provinceCodeToIdx: '',
          provinceCodeTo: '',
          // 市
          cityCodeToIdx: '',
          cityCodeTo: '',
          // 区,
          areaCodeTo: '',
          // 详细地址
          addressTo: '',
          // 选择默认价格
          openDefault: 0,
          // 选择周末价格
          openWeekend: 0,
          // 选择特殊日期价格
          openDate: 0,
          // 成人默认价格
          defaultAdultPrice: '',
          // 默认佣金
          defaultCommission: '',
          // 儿童默认价格
          defaultChildrenPrice: '',
          // 成人周末价格
          weekendAdultPrice: '',
          // 周末佣金
          weekendCommission: '',
          // 儿童周末价格
          weekendChildrenPrice: '',
          // 成人指定日期价格
          dateAdultPrice: '',
          // 指定日期佣金
          dateCommission: '',
          // 儿童指定日期价格
          dateChildrenPrice: '',
          // 指定日期
          dateBetween: [],
          // 运营时间
          operationTime: ['08:00:00', '20:00:00'],
          // 售票截至时间
          ticketDeadline: '',
          // 售票运营时间
          ticketingTime: []
        }
      }
    },
    mounted(){
      this.form['id'] = this.$router.currentRoute.query['id'] || '';
      if (this.$router.currentRoute.path.indexOf('add') > 0) {
        this.pageType = 'add'
      } else {
        this.pageType = 'edit'
      }
      this.loadCarTypeList();
    },
    methods: {
      // 加载车辆类型列表
      loadCarTypeList(){
        (async () => {
          const result = await this.$service.applicationGetAllCarType();
          if (result.code === 0) {
            this.carTypeList = result.data;
            this.loadDriverList();
          }
        })();
      },
      // 加载司机列表
      loadDriverList(){
        (async () => {
          const result = await this.$service.applicationGetAllDriver();
          if (result.code === 0) {
            this.driverList = result.data;
            this.loadProvinceList();
          }
        })();
      },
      // 加载省市区列表
      loadProvinceList(){
        (async () => {
          const result = await this.$service.applicationGetProvinceList();
          if (result.code === 0) {
            this.provinceList = result.data;
            if (this.pageType === 'edit') {
              this.loadData();
            }
          }
        })();
      },
      // 加载路线信息
      loadData(){
        (async () => {
          const result = await this.$service.applicationGetDailyRouteDetails({id: this.form['id']});
          if (result.code === 0) {
            const data = Object.assign({}, result.data);
            result.data['operationTime'] && (data['operationTime'] = result.data['operationTime'].split(','));
            result.data['ticketingTime'] && (data['ticketingTime'] = result.data['ticketingTime'].split(','));
            result.data['dateBetween'] && (data['dateBetween'] = result.data['dateBetween'].split(','));
            // 将获取的司机转换为页面需要的int数组
            data['driver'] = result.data['driver'].split(',');
            for (let i = 0; i < data['driver'].length; i++) {
              data['driver'][i] = parseInt(data['driver'][i])
            }
            for (let i = 0; i < this.provinceList.length; i++) {
              if (this.provinceList[i].code === data['provinceCodeFrom']) {
                data['provinceCodeFromIdx'] = i;
                this.FromCityList = this.provinceList[i]['children'];
                for (let j = 0; j < this.provinceList[i]['children'].length; j++) {
                  if (this.provinceList[i]['children'][j].code === data['cityCodeFrom']) {
                    data['cityCodeFromIdx'] = j;
                    this.FromAreaList = this.provinceList[i]['children'][j]['children'] || [];
                  }
                }
              }
              if (this.provinceList[i].code === data['provinceCodeTo']) {
                data['provinceCodeToIdx'] = i;
                this.ToCityList = this.provinceList[i]['children'];
                for (let j = 0; j < this.provinceList[i]['children'].length; j++) {
                  if (this.provinceList[i]['children'][j].code === data['cityCodeTo']) {
                    data['cityCodeToIdx'] = j;
                    this.ToAreaList = this.provinceList[i]['children'][j]['children'] || [];
                  }
                }
              }
            }
            this.form = Object.assign(this.form, data);
          }
        })();
      },
      // 省份选择监听e:选择的index,params:出发地还是终点
      provinceSelectChange(e, params){
        // console.log(e, params);
        this[params + 'CityList'] = this.provinceList[e]['children'];
        this.form['provinceCode' + params] = this.provinceList[e]['code'];
        this.form['cityCode' + params + 'Idx'] = '';
        this.form['cityCode' + params] = '';
        this.form['areaCode' + params] = '';
      },
      // 市级选择监听e:选择的index,params:出发地还是终点
      citySelectChange(e, params){
        // console.log(e, params);
        this[params + 'AreaList'] = this[params + 'CityList'][e]['children'] || [];
        this.form['cityCode' + params] = this[params + 'CityList'][e]['code'];
        this.form['areaCode' + params] = '';
      },
      // 车票选择监听
      radioClick(params){
        this.form[params] = this.form[params] ? 0 : 1
      },
      // 提交
      onSubmit() {
        this.$refs.form.validate(valid => {
          if (valid) {
            // let checkShifts = true;
            // if (this.form['shifts'] >= 60) {
            //   if (60 % (this.form['shifts'] % 60) !== 0) {
            //     checkShifts = false;
            //   }
            // } else if (this.form['shifts'] < 0) {
            //   checkShifts = false;
            // } else {
            //   if (60 % this.form['shifts'] !== 0) {
            //     checkShifts = false;
            //   }
            // }
            // if (!checkShifts){
            //   this.$message.error('输入班次间隔时间不合理');
            //   return;
            // }
            if (this.form['ticketNumber'] > this.form['rideNumber']){
              this.$message.error('可售车票数量应小于等于荷载数');
              return;
            }
            this.loading = true;
            (async () => {
              const params = Object.assign({}, this.form);
              params['driver'] && (params['driver'] = params['driver'].join(','));
              params['ticketingTime'] && (params['ticketingTime'] = params['ticketingTime'].join(','));
              params['dateBetween'] && (params['dateBetween'] = params['dateBetween'].join(','));
              // console.log(params);
              let result = null;
              if (this.pageType === 'add') {
                result = await this.$service.applicationAddDailyRoute(params);
              } else {
                result = await this.$service.applicationModifyDailyRoute(params);
              }
              this.loading = false;
              if (result.code === 0) {
                this.$message.success('操作成功~');
                this.$router.back();
              } else {
                this.$message.error(result.msg);
              }
            })();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }
    }
  }
</script>

<style lang="scss" type="text/scss" scoped>
  @import '../../../styles/index.scss';
  .ticket{
    .item{
      margin-bottom: 30px;
    }
    span{
      font-weight: 500;
      line-height: 38px;
    }
    .el-input{
      margin-top: 1px;
      width: 190px;
      margin-left: 10px;
      .span{
        margin-right: 10px;
        line-height: 40px;
      }
    }
  }
</style>
